package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.adpter.FinishListAdapter;
import com.xn.app.muying.bean.FinishListBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 已完成化验单列表
 * Created by Administrator on 2017/1/4.
 */
public class FinishListActivity extends BaseActivity implements View.OnClickListener, MyListView.IXListViewListener {

    private MyListView lv;
    //数据库
    private DBManager db = null;
    //加载框
    AlertDialog dialog;
    private FinishListAdapter adapter;
    private ArrayList<FinishListBean> list = new ArrayList<>();
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finishlist);
        db = new DBManager(this);
        initView();
    }

    private void initView() {
        TextView title_name = (TextView) findViewById(R.id.title_name);
        ImageView img_back = (ImageView) findViewById(R.id.img_back);
        lv = (MyListView) findViewById(R.id.activity_finishlist_lv);
        title_name.setText(getIntent().getStringExtra("DisplayName"));
        img_back.setOnClickListener(this);
        adapter = new FinishListAdapter(this);
        lv.setAdapter(adapter);
        if (NetworkUtil.isNetworkAvailable(FinishListActivity.this)) {
            dialog = new MyAlertDialog().ShowDialog(FinishListActivity.this, R.layout.dialog_loading);
            FinishSheetList(getIntent().getStringExtra("id"));//已完成化验单数据详情列表下载
        } else {
            ToastUtil.showToast(FinishListActivity.this, R.string.no_network_hint);
        }
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                intent.putExtra("id", list.get(i).getId());
                intent.putExtra("exceptionCount", list.get(i).getExceptionCount());
                if (list.get(i).getExceptionCount().equals("0")) {
                    intent.setClass(FinishListActivity.this, SheetUnexceptionInfoActivity.class);
                    startActivity(intent);
                } else {
                    intent.setClass(FinishListActivity.this, SheetExceptionInfoActivity.class);
                    startActivity(intent);
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
        }
    }

    private void FinishSheetList(final String id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.FinishSheetInfo(id, currentPage, number)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    onJsonData(msg.obj.toString());
                    break;
                case 1:
                    ToastUtil.showToast(FinishListActivity.this, "获取数据失败");
                    break;
            }
        }
    };

    private void onJsonData(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            //获取数据总量
            if (totalCount == 0) {
                totalCount = Integer.parseInt(jsonObject.get("totalCount").toString());
            }
            JSONArray items = jsonObject.getJSONArray("items");

            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String processStatus = object.optString("processStatus");
                String reporterDate = object.optString("reporterDate");
                String reportCategoryDisplayName = object.optString("reportCategoryDisplayName");
                String reportCategoryId = object.optString("reportCategoryId");
                String exceptionCount = object.optString("exceptionCount");
                String id = object.optString("id");
                FinishListBean bean = new FinishListBean();
                bean.setProcessStatus(processStatus);
                bean.setReporterDate(reporterDate);
                bean.setReportCategoryDisplayName(reportCategoryDisplayName);
                bean.setReportCategoryId(reportCategoryId);
                bean.setExceptionCount(exceptionCount);
                bean.setId(id);
                list.add(bean);
            }
            lv.setPullLoadEnable(true);
            lv.setXListViewListener(FinishListActivity.this, totalCount, currentPage, number);
            adapter.getData(list);
            if (lv.getVisibility() == View.GONE) {
                lv.setVisibility(ListView.VISIBLE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //上拉加载更多
    @Override
    public void onLoadMore() {
        if (totalCount > currentPage * number) {
            currentPage = currentPage + 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(AppConstant.THREAD_SLEEP);
                        FinishSheetList(getIntent().getStringExtra("id"));//已完成化验单数据详情列表下载
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            onLoad();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        lv.stopLoadMore();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
